Skip to content

perf: compute several percentiles in one counts scan - #72

Merged
alexvictoor merged 5 commits into
masterfrom
perf/multi-percentile-scan
Nov 15, 2026
Merged

alexvictoor merged 5 commits into
masterfrom
perf/multi-percentile-scan

Conversation

@alexvictoor

@alexvictoor alexvictoor commented Nov 15, 2026 •

Copy link
Copy Markdown
Member

Summary

summary (and so toJSON) asked for eight percentiles one at a time, and each call scanned the counts. One call now answers all of them with one scan.

 toSummary
-  getValueAtPercentile(50)      # scan 1
-  getValueAtPercentile(75)      # scan 2
-  ...
-  getValueAtPercentile(99.999)  # scan 8
+  getValuesAtPercentiles(50, 75, 90, 97.5, 99, 99.9, 99.99, 99.999)  # scan 1
flowchart TD
    A["thresholds = countAtPercentile(p) for each p, shared with getValueAtPercentile"] --> B["positions sorted by threshold, NaN left out (result stays 0)"]
    B --> C["i = next index that may hold a count, up to highestNonZero (bounds from #70; packed storage skips empty subtrees, #69)"]
    C --> D{"flat storage and next threshold beyond this 64-byte block?"}
    D -- yes --> E["total += SIMD block sum, skip the block"] --> C
    D -- no --> F["total += count(i)"]
    F --> G{"total reaches the next threshold?"}
    G -- yes --> H["result[position] = value at i (same 0.0 / highestEquivalent rule)"] --> G
    G -- no --> C
    C -- all resolved --> R["results in input order"]
Loading
src/
├── Histogram.ts          # interface member, toSummary uses it
├── JsHistogram.ts        # one loop for 8/16/32/64, Float64 and packed
├── PackedHistogram.ts    # its getValueAtPercentile (from #69) shares the
│                         # threshold and value helpers of that loop
└── wasm/index.ts         # pinned scratch Float64Array, reused across calls:
                          # the minimal runtime only collects on destroy
assembly/
└── Histogram.ts          # same loop; skips 64-byte SIMD blocks the next
                          # threshold does not reach; results written in place

getValuesAtPercentiles(...percentiles) takes the percentiles as varargs, so histogram.getValuesAtPercentiles(50, 99, 99.9) reads like the single call and a list is passed with the spread operator. The wasm boundary still receives one Float64Array.

countAtPercentile is shared with getValueAtPercentile and now clamps to [0, 100] on both sides (see Merge Danger).

Rebased on #69. The getValueAtPercentile override that #69 added to PackedHistogram computed its own threshold without the clamp, and ulp() of a negative number is NaN, so a negative percentile returned 0 on a JS packed histogram while getValuesAtPercentiles returned the lowest recorded value. CI caught it on the merge commit. The override now uses the shared helpers, and getValuesAtPercentiles walks the counts through nextNonZeroIndexInRange, so packed histograms skip their empty subtrees there too.

Evidence

  • Before: npx vitest bench src/bench/histogram-json-percentile.bench.ts on master, toSummary ops/s.
    After: same bench on this branch.
Histogram master branch
Int32 (JS) 10,166 – 11,087 62,463 5.9x
WASM 32 191,005 – 201,396 475,483 2.4x
Packed (JS) 822 – 969 6,235 7.0x
WASM Packed 3,211 – 3,315 15,861 4.9x

Measured after the rebase on #69 (master at bdfa37d, two runs; branch at the rebased head). The JS rows gain from the nextNonZeroIndexInRange walk: on a sparse Int32 histogram, getValuesAtPercentiles with eight percentiles went from 7.6k – 12k to 33.9k ops/s against the index-by-index scan of the first version, and from 1.8k – 3.2k to 6.0k on a JS packed one.

The single-percentile bench (histogram-percentile.bench.ts) moves by about 40% between runs on this machine, so no change is claimed for getValueAtPercentile.

  • Before: no test for several percentiles in one call.
    After: src/Histogram.valuesAtPercentiles.spec.ts, 47 tests over the five implementations. Fast-check property: getValuesAtPercentiles(...list) equals list.map(getValueAtPercentile) for unsorted and duplicate percentiles in [-10, 110] plus 0 / 100 / 150 / -1 / ±Infinity, no argument, empty histogram, NaN (also with a unit magnitude above 0), input order, the destroyed-histogram guard on WASM, and summary against the per-percentile values.
npm test            331 passed
npm run astest:ci   15377 / 15377
npm run typecheck   clean

Merge Danger

Door: two-way

Additive method, summary returns the same values as before. A revert restores the eight scans.

Blast Radius: interface

Histogram gains a required member, so an external class that implements the interface by hand stops compiling until it adds getValuesAtPercentiles. Observable change to getValueAtPercentile itself: a negative percentile now returns the lowest recorded value on JS (as on WASM and in Java) instead of 0, and NaN returns 0 on WASM instead of the value at index 0.

🤖 Generated with Claude Code

@alexvictoor
alexvictoor marked this pull request as ready for review November 15, 2026 19:20
alexvictoor and others added 5 commits November 15, 2026 22:07
Add getValuesAtPercentiles(percentiles) to every histogram implementation (JS, packed, Float64, WASM). One bounded scan of the counts fills all requested percentiles, in input order, instead of one scan per percentile. The summary getter uses it, so the eight summary percentiles take one pass.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
- Percentiles are clamped to [0, 100] in countAtPercentile on both sides,
  so negative and -Infinity percentiles give the lowest value in JS and
  WASM alike (JS used to return 0 because ulp(x <= 0) is NaN, and in the
  AS batch path a -Infinity entry produced a NaN threshold that blocked
  every later entry).
- The AS getValueAtPercentile returns 0 for a NaN percentile, as the JS
  one does, instead of reporting the value at index 0.
- The AS batch path allocates nothing per call: thresholds and the sorted
  positions live in module-level scratch state, the results overwrite the
  input array, and the positions are sorted with Array#sort rather than
  an insertion sort.
- The wasm wrapper reuses a pinned scratch Float64Array instead of
  allocating an input array and a result array per call (the minimal
  runtime only collects on destroy), and throws on a destroyed histogram.
- newUint8Array and the scratch array share newArrayBufferView; the
  64-byte block sum and the percentile-to-value rule are shared between
  the single and batch methods.
- Tests cover negative, infinite and NaN percentiles (also with a unit
  magnitude above 0) and the destroyed-histogram guard.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…onventions

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
`histogram.getValuesAtPercentiles(50, 99, 99.9)` reads like the single
percentile call; a list is passed with the spread operator. The wasm
boundary still receives one Float64Array, so the AS side is unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Master now overrides getValueAtPercentile in PackedHistogram to walk only
the populated indexes. That override computed its own threshold without
clamping negative percentiles to 0, and ulp() of a negative number is NaN,
so a negative percentile returned 0 on a packed histogram while
getValuesAtPercentiles returned the lowest recorded value. Both now share
countAtPercentile and valueAtPercentileIndex, and getValuesAtPercentiles
walks the counts through nextNonZeroIndexInRange so packed histograms skip
their empty subtrees there too.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
@alexvictoor
alexvictoor force-pushed the perf/multi-percentile-scan branch from 7d64036 to 8e139f3 Compare November 15, 2026 21:17
@alexvictoor
alexvictoor merged commit 41cc6e6 into master Nov 15, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant